/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.economy.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;

import ar.uba.fi.posgrado.common.dao.AbstractDAO;
import ar.uba.fi.posgrado.common.dao.DAOException;
import ar.uba.fi.posgrado.economy.dao.PayDAO;
import ar.uba.fi.posgrado.economy.model.Pay;

/**
 * Implementacion de {@link PayDAO}
 * 
 * @author nicolas.gonzalez
 * @see PayDAO
 * @see AbstractDAO
 */
public class PayDAOImpl extends AbstractDAO<Pay> implements PayDAO {

	/**
	 * @see ar.uba.fi.posgrado.common.dao.AbstractDAO#getClazz()
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected Class getClazz() {
		return Pay.class;
	}

	/**
	 * @see ar.uba.fi.posgrado.economy.dao.PayDAO#findByTeacherId(java.lang.Long)
	 */
	@SuppressWarnings("unchecked")
	public List<Pay> findByTeacherId(Long id) throws DAOException {
		final StringBuffer nativeQuery = new StringBuffer(
				"select {pago.*} from EGRESO pago where pago.ID_HONORARIO in (")
				.append(" select ID from HONORARIO where ID_DOCENTE ='")
				.append(id).append("');");
		List<Pay> response = null;

		try {
			// Se hace con una inner class para poder usar la NativeSQL. Lo
			// mismo pasaria con un Criteria
			response = this.getHibernateTemplate().executeFind(
					new HibernateCallback() {
						/** @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session) */
						public Object doInHibernate(Session session)
								throws HibernateException, SQLException {
							SQLQuery query = session.createSQLQuery(
									nativeQuery.toString()).addEntity("pago",
									Pay.class);
							return query.list();
						}
					});
		} catch (DataAccessException e) {
			throw new DAOException(
					"Excepcion al buscar los pagos realizados al docente con id: "
							+ id + ". Mensaje: " + e.getMessage(), e);
		}

		return response;
	}

}
